package com.tencreat.service.mall.impl;

import cn.hutool.extra.cglib.CglibUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.domain.account.MallStore;
import com.tencreat.domain.mall.MallCategory;
import com.tencreat.domain.mall.MallGoods;
import com.tencreat.domain.mall.MallStoreGoods;
import com.tencreat.domain.mall.MallGoodsNorms;
import com.tencreat.domain.mall.MallSetmealNorms;
import com.tencreat.domain.mall.dto.*;
import com.tencreat.domain.mall.vo.*;
import com.tencreat.mapper.mall.MallShopGoodsMapper;
import com.tencreat.service.account.IMallStoreService;
import com.tencreat.service.mall.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zixin
 * 店铺商品
 */
@Service
public class MallShopGoodsImpl extends ServiceImpl<MallShopGoodsMapper, MallGoods> implements IMallShopGoodsService {

    @Autowired
    private IMallStoreGoodsService mallStoreGoodsService;//商品信息
    @Autowired
    private IMallGoodsNormsService mallGoodsNormsService;
    @Autowired
    private IMallCategoryService mallCategoryService;//类目


    @Autowired
    private IMallGoodsService goodsService;//商品信息

    @Autowired
    private IMallStoreService mallStoreService;

    @Override
    public Page<MallStoreGoodsVO> list(IPage<?> page, MallStoreGoodsDTO dto) {
        if (dto.getSortStr() != null && dto.getSortDesc() != null){
            if ("descending".equals(dto.getSortDesc())){
                dto.setSortDesc("desc");
            }else {
                dto.setSortDesc("asc");
            }
        }
        Page<MallStoreGoodsVO> poPage = baseMapper.page(page, dto);
//        poPage.getRecords().forEach(item ->{
//            List<MallGoodsNorms> list = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getGoodsId, item.getId()).list();
//            long sum = list.stream().map(l -> l.getInventory()).collect(Collectors.toList()).stream().mapToLong(Long::longValue).sum();
//            item.setRetailPrice(list.get(0).getRetailPrice());
//            item.setSupplyPrice(list.get(0).getSupplyPrice());
//            item.setInventory(Integer.parseInt(sum+ ""));
//        });
        return poPage;
    }

    @Override
    public Page<MallStoreGoodsVO> listAudit(IPage<?> page, MallStoreGoodsAuditDTO dto) {
        if (dto.getSortStr() != null && dto.getSortDesc() != null){
            if ("descending".equals(dto.getSortDesc())){
                dto.setSortDesc("desc");
            }else {
                dto.setSortDesc("asc");
            }
        }
        Page<MallStoreGoodsVO> mallStoreGoodsPOPage = baseMapper.pageAudit(page, dto);
//        mallStoreGoodsPOPage.getRecords().forEach(item -> {
//            List<MallGoodsNorms> list = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getGoodsId, item.getId()).list();
//            long sum = list.stream().map(l -> l.getInventory()).collect(Collectors.toList()).stream().mapToLong(Long::longValue).sum();
////            item.setRetailPrice(list.get(0).getRetailPrice());
//            //item.setSupplyPrice(list.get(0).getSupplyPrice());
////            item.setInventory(Integer.parseInt(sum+ ""));
//        });
        return mallStoreGoodsPOPage;
    }


    @Override
    public List<MallStoreGoodsVO> list(MallStoreGoodsDTO dto) {
        return baseMapper.list(dto);
    }

    @Override
    public MallGoodsAllVO query(Long id) {
        MallGoodsAllVO mallGoodsAllVO = new MallGoodsAllVO();
        MallGoods goods = baseMapper.selectById(id);
        MallGoodsDTO mallGoodsVO = new MallGoodsDTO();
        if (goods != null) {
            LambdaQueryChainWrapper<MallCategory> mallCategoryLambda = mallCategoryService.lambdaQuery();
            mallCategoryLambda.eq(MallCategory::getId, goods.getCategoryId());
            MallCategory child = mallCategoryLambda.one();
            mallCategoryLambda = mallCategoryService.lambdaQuery();
            mallCategoryLambda.eq(MallCategory::getId, child.getPid());
            MallCategory parent = mallCategoryLambda.one();
            BeanUtils.copyProperties(goods, mallGoodsVO);
            mallGoodsVO.setCategoryId(Arrays.asList(parent.getId(), child.getId()));


        }
        mallGoodsAllVO.setMallGoodsVO(mallGoodsVO);

        return mallGoodsAllVO;
    }
    @Override
    public MallStoreGoodsQueryVO queryByAdmin(Long id) {
        MallGoods mallGoods = lambdaQuery().eq(MallGoods::getId, id).one();
        if (mallGoods == null) {
            throw new CustomException("商品已失效或已删除");
        }
        MallStoreGoodsQueryVO result = CglibUtil.copy(mallGoods, MallStoreGoodsQueryVO.class);

        return result;
    }

    @Override
    public boolean add(MallGoodsAddDTO dto) {
        MallGoods goods = dto.getGoods();

        if (goods != null) {
            if (dto.getNorms() == null || dto.getNorms().size() < 0) {
                throw new CustomException("规格信息不能为空");
            }
            goods.setPicUrl(JSONObject.parseObject(goods.getGallery(), ArrayList.class).get(0).toString());
            goods.setAuditStatus(0);
            goods.setStore(1L);
            goods.setOrderType("0");
            goods.setGoodsType("0");
            goods.setCreateTime(LocalDateTime.now());
            goods.setUpdateTime(LocalDateTime.now());
            goods.setIsOnSale(0);
            goods.setOrderType("0");
            goods.setGoodsType("0");
            goods.setSupplier(0L);
            goods.setChain(0);
            goods.setGoodsSn(TenCreatUtil.getOrderNo());
            goods.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());

            MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getUserId, SecurityUtils.getLoginUser().getUser().getUserId()).one();
            goods.setStoreId(mallStore.getId());

            baseMapper.insert(goods);
            List<MallGoodsNorms> norms = dto.getNorms();
            for (MallGoodsNorms goodsNorms : norms) {
                goodsNorms.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
                goodsNorms.setGoodsId(goods.getId());
            }
            mallGoodsNormsService.saveOrUpdateBatch(norms);
        }
//        baseMapper.updateById(goods);

        return true;
    }

    @Override
    public List<Integer> queryCount(Long userId){
        // 上架中数量
        Integer count = goodsService.lambdaQuery().eq(MallGoods::getIsOnSale, 1).eq(MallGoods::getAuditStatus, 1).eq(MallGoods::getUserId,userId).count();
        // 下架数量
        Integer lowerCount = goodsService.lambdaQuery().eq(MallGoods::getIsOnSale, 0).eq(MallGoods::getAuditStatus, 1).eq(MallGoods::getUserId,userId).count();
        // 总数量
        int totalCount = (count != null ? count : 0) + (lowerCount != null ? lowerCount : 0);

        List<Integer> counts = new ArrayList<>();
        counts.add(totalCount);
        counts.add(count);
        counts.add(lowerCount);

        return counts;
    }

    @Override
    public List<Integer> queryAuditCount(Long userId){
        // 未审核
        Integer count = goodsService.lambdaQuery().eq(MallGoods::getAuditStatus, 0).eq(MallGoods::getUserId,userId).count();
        // 已拒绝
        Integer lowerCount = goodsService.lambdaQuery().eq(MallGoods::getAuditStatus, 2).eq(MallGoods::getUserId,userId).count();
        // 总数量
        int totalCount = (count != null ? count : 0) + (lowerCount != null ? lowerCount : 0);

        List<Integer> counts = new ArrayList<>();
        counts.add(totalCount);
        counts.add(count);
        counts.add(lowerCount);

        return counts;
    }

}
